<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Vstar
 *
 * @author dragon.hu add @2016.4.5
 */
require_once 'BaseChannel.php';

//新马SDK  服务器IP：52.77.57.174
class Vstar implements BaseChannel 
{	
	function __construct() 
	{
		//echo "construct";
	}

	//put your code here
	function android($data) 
	{
		$paymentKey="327500d1bab9dc12f7dd1b1d3ffb1db8b15be219"; //client secret
		$ret = $this->paymentCallBack($paymentKey, ANDROID);
		echo $ret;
	}

	function ios($data) 
	{
		$paymentKey=""; //
		$ret = $this->paymentCallBack($paymentKey, IOS);
		echo $ret;
	}

	function paymentCallBack($paymentKey, $platform)
	{
		//include CONFIGPATH.'config.php';
		require (CONFIGPATH . 'db.php');
		$paydbconn = new Database($config['payment_db']);
		$accountConn = new Database($config['center_db']);
		
		$orderLog = new ChargeOrder();
		$orderLog->log("vstar", $_REQUEST);
		
		$orderType = $_REQUEST['orderType'];  //付款方式 1 Google Play 2 Apple Store 3 第三方 4 游戏官网充值(Web)
		$created = $_REQUEST['created'];  //订单产生时间(10位时间戳)
		$orderId = $_REQUEST['orderId'];  //我方产生的唯一订单(开发商判断是否重复订单)
		$serverId = $_REQUEST['serverId'];  //游戏区服ID，(开发商接入VstarGame SDK，支付时传入)
		$account = $_REQUEST['account'];  //VstarGame平台账号ID，由VstarGame SDK提供
		$roleId = $_REQUEST['roleId'];  //角色ID，(开发商接入VstarGame SDK，支付时传入)
		$currency = $_REQUEST['currency'];  //币种 USD
		$amount = $_REQUEST['amount'];  //金额 9.99
		$extra = $_REQUEST['extra'];  //拓展字段 (透传值) (游戏官网充值为空字符串) (开发商接入VstarGame SDK，支付时传入)
		$present = $_REQUEST['present'];  //赠送比例，0.2 多送20%元宝
		$test = $_REQUEST['test'];  //ok 表示测试订单no 表示正常订单
		$flag = $_REQUEST['flag'];  //验签字符串
		
		//对amount进行汇率转换
		//$tmprate = $config['currency_list'][4]['rate'];  //4表示美元，在config.php中配置，数组顺序最好不要变动
		//$amount *= $tmprate;
		
		$mysign = md5($orderType.$created.$orderId.$serverId.$account.$roleId.$currency.$amount.$extra.$present.$test.$paymentKey);
		$return = array();
		
		/*求别再改需求了╮(╯▽╰)╭2016.4.27 modify
		 * 第三方充值：
			除点击月卡和十年卡进行第三方充值外，其他均按就近档匹配发送钻石
		官网充值：
			官网充值不匹配月卡和十年卡（即不能充值月卡和十年卡）*/
		if($flag == $mysign)  
		{ //验证通过
			 if (/*empty($orderType) &&*/ empty($extra))  //表示是官网充值
			 {
			 	if ($present != 0)
			 	{
			 		$amount = $amount * (1 + $present);
			 	}
			 	$nowtime = time();
			 	$orderid = "WebVstar_".$serverId.'_'.$roleId.'_'.$nowtime;  //拼接自己的orderid
			 	//通过account找到accountid
			 	$sql = "SELECT id FROM account WHERE name = '$account'";
			 	$one = $accountConn->one($sql);
			 	$myaccountId = $one['id'];
			 	//var_dump($orderid);
			 	$result = $this->insertOrder($paydbconn, $orderLog, $amount, $orderid, $serverId, $roleId, $myaccountId,  "WebVstar", ANDROID);
			 	if ($result)
			 	{
			 		//支付成功
			 		$return['status'] = true;
			 		$return['code'] = 1;
			 		$return['contents'] = 'success';
			 		$orderLog->log("vstar",array("order"=>$extra,"money"=>$amount,"serverresult"=>"official website pay success"));
			 	}
			 	else
			 	{
			 		$return['status'] = false;
			 		$return['code'] = 104;
			 		$return['contents'] = 'other';
			 		$orderLog->log("vstar",array("order"=>$extra,"money"=>$amount,"serverresult"=>"official website pay failed"));
			 	}
			 }
			 else
			 {
			 	//先确认点击的是否是月卡或十年卡
			 	$one = $paydbconn->one("SELECT * FROM tt_payment WHERE serverid = '$serverId' AND roleid = $roleId AND orderid = '$extra'");
			 	if (empty($one))
			 	{
			 		$return['status'] = false;
			 		$return['code'] = 104;
			 		$return['contents'] = 'other';
			 		$orderLog->log("vstar", "get productid from tt_payment failed! roleid=$roleId, serverid=$serverId, money=$amount");
			 		$ret = json_encode($return);
			 		return $ret;
			 	}
			 	$originProductId = $one['product_id'];
			 	
			 	//通过money验证是哪个产品
			 	$dyndb = getTmpDbConnect(PLATFORM_ALL, 'all', $serverId, DBTYPE_DYNAMIC);
			 	if ($dyndb == false)
			 	{
			 		$return['status'] = false;
			 		$return['code'] = 104;
			 		$return['contents'] = 'other';
			 		$orderLog->log("vstar", "gettmpdbconnet dyn failed! roleid=$roleId, serverid=$serverId, money=$amount");
			 		$ret = json_encode($return);
					return $ret;
			 	}
			 	
			 	//匹配规则，小于最小，大于最大的
			 	$sql = "SELECT * FROM dynamic_act_charge";
			 	$dyndb->query($sql);
			 	$chargedata = array();
			 	$allInfoData = array();
			 	while ($n = $dyndb->get_array())
			 	{
			 		$allInfoData[$n['product_id']] = $n;
			 		if ($n['kind'] == 1 || $n['kind'] == 2)  continue;  //除了月卡和十年卡
			 		$chargedata[$n['product_id']] = $n['rmb'];
			 	}
			 	
			 	if ($allInfoData[$originProductId]['kind'] == 1 || $allInfoData[$originProductId]['kind'] == 2)  //月卡和十年卡的kind
			 	{
			 		if ($present != 0)
			 		{
			 			$amount = $amount * (1 + $present);
			 		}
			 		//进行发货
			 		if(false == $this->recordOrder($orderLog, $paydbconn, STATUS_SUCCESS, $amount, $extra, $orderId))//recordOrder(STATUS_SUCCESS, $amount, $extra, "vstar", $platform,$orderId))
			 		{
			 			$return['status'] = false;
			 			$return['code'] = 104;
			 			$return['contents'] = 'other';
			 			$orderLog->log("vstar",array("order"=>$extra,"money"=>$amount,"monthcard or tenyearcard productid serverresult"=>"faild"));
			 		}else
			 		{
			 			//支付成功
			 			$return['status'] = true;
			 			$return['code'] = 1;
			 			$return['contents'] = 'success';
			 			$orderLog->log("vstar",array("order"=>$extra,"money"=>$amount,"monthcard or tenyearcard productid serverresult"=>"success"));
			 		}
			 	}
			 	else  //其他情况
			 	{
			 		asort($chargedata);
			 		$targetproductid = 1;
			 		
			 		$count = 0;
			 		$mink = 0;
			 		foreach ($chargedata as $k=>$v)
			 		{
			 			if($count == 0)
			 			{
			 				$comparev = $v;
			 				$mink = $k;
			 			}
			 			else
			 			{
			 				if ($v < $comparev)
			 				{
			 					$comparev = $v;
			 					$mink = $k;
			 				}
			 			}
			 			$count++;
			 		}
			 		$targetproductidext = $mink;  //默认值是花费最小的product_id
			 					 		
			 		foreach ($chargedata as $k=>$v)  //找出最接近的一个
			 		{
			 			$targetproductid = $k;
			 			if ($amount < $v)
			 			{
			 				break;
			 			}
			 			$targetproductidext = $targetproductid;  //找出最接近的product_id
			 		}
			 		//要更新目标product_id
			 		if ($present != 0)
			 		{
			 			$amount = $amount * (1 + $present);
			 		}
			 		//进行发货
			 		if(false == $this->VstarOrder($orderLog, $paydbconn, $targetproductidext, STATUS_SUCCESS, $amount, $extra, $orderId))
			 		{
			 			$return['status'] = false;
			 			$return['code'] = 104;
			 			$return['contents'] = 'other';
			 			$orderLog->log("vstar",array("order"=>$extra,"money"=>$amount,"ignore productid serverresult"=>"faild"));
			 		}else
			 		{
			 			//支付成功
			 			$return['status'] = true;
			 			$return['code'] = 1;
			 			$return['contents'] = 'success';
			 			$orderLog->log("vstar",array("order"=>$extra,"money"=>$amount,"ignore productid serverresult"=>"success"));
			 		}
			 	}
			 	
			 }
			 
		} 
		else 
		{
			//"$sig验证失败"
			$return['status'] = false;
			$return['code'] = 100;
			$return['contents'] = 'Signature error';
			$orderLog->log("vstar","  order:$extra  sign error sign:$flag mysign:$mysign");
		}
		$ret = json_encode($return);
		return $ret;
	}
	
	function insertOrder($paydb, $orderlog, $money, $orderid, $serverid, $roleid, $accountid, $channelid, $platform,$thirdorderid='')
	{
		require (CONFIGPATH . 'db.php');
		$tmpdb = new Database($config['payment_db']);
		//通过充值金额找到对应的商品
		$dyndb = getTmpDbConnect(PLATFORM_ALL, 'all', $serverid, DBTYPE_DYNAMIC);
		if ($dyndb == false)
		{
			$orderlog->log("vstar", "Vstar insertOrder:get product failed!!!! roleid=$roleid, serverid=$serverid, money=$money");
			return;
		}
		//匹配规则，小于最小，大于最大的
		$sql = "SELECT * FROM dynamic_act_charge";
		$dyndb->query($sql);
		$chargedata = array();
		while ($n = $dyndb->get_array())
		{
			if ($n['kind'] == 1 || $n['kind'] == 2)  continue;  //除了月卡和十年卡
			$chargedata[$n['product_id']] = $n['rmb'];
		}
		asort($chargedata);
		$targetproductid = 1;
		
		$count = 0;
		$mink = 0;
		foreach ($chargedata as $k=>$v)
		{
			if($count == 0)
			{
				$comparev = $v;
				$mink = $k;
			}
			else
			{
				if ($v < $comparev)
				{
					$comparev = $v;
					$mink = $k;
				}
			}
			$count++;
		}
		$targetproductidext = $mink;  //默认值是花费最小的product_id
		
		foreach ($chargedata as $k=>$v)
		{
			$targetproductid = $k;
			if ($money < $v)
			{
				break;
			}
			$targetproductidext = $targetproductid;  //找出最接近的product_id
		}
		
		//$row = $tmpdb->one($sql);
		$nowtime = date('Y-m-d H:i:s', time());
		$sql = "INSERT INTO {pre}payment(orderid,serverid,roleid,accountid,create_time,status,channel,platform,appid,money,finish_time,product_id) VALUES
		('$orderid','$serverid','$roleid','$accountid','$nowtime','1','$channelid','$platform','0','$money','$nowtime','$targetproductidext')";
		$res = $paydb->execute($sql);
		if ($res == false)
		{
			$orderlog->log("error", "Vstar insertOrder:execute sql failed! ".$sql);
			return false;
		}
	
		$serverInfo = $paydb->one("SELECT * FROM {pre}areasample WHERE `id`='" .$serverid. "'");
		$one['orderid'] = (string) $orderid;
		$one['roleid'] = (int) $roleid;
		$one['channel'] = (string) $channelid;
		$one['money'] = (string) $money;
		$one['platform'] = (int) $platform;
		$one['finish_time'] = (string)$nowtime;
		$one['product_id'] = (int)$targetproductidext;
	
		//第几次充值
		$paytimes = 0;
		$sql = "SELECT * FROM {pre}payment WHERE serverid = ".$serverid." AND roleid='".$roleid."'";
		$paydb->query($sql);
		$rolepayarr = array();
		while ($n = $paydb->get_array())
		{
			$rolepayarr[] = $n;
		}
		for ($i = 0; $i < count($rolepayarr); $i++)
		{
			if (isset($rolepayarr[$i]['money']))
			{
				$paytimes += 1;
			}
		}
	
		$one['paytimes'] = $paytimes;  //累计支付次数
		$datas[] = $one;
		$json_str = json_encode($datas);
		$json_str = str_replace(" ", "%20", $json_str);
	
				$strResult = vpost($serverInfo['host'] . "json_str=$json_str&action=45", 10);     //请求游戏服务器发放充值
		//推送游戏服务器超时或者失败
		if ($strResult === FALSE || $strResult=="fail") {
		//echo "error:area sending fail ";
			//写log
			$tmpstr = http_build_query($one);
			$orderlog->log("error", "Vstar insertOrder:post error!!!".$tmpstr);
			return false;
		}
		return true;
	}
	
	//因为IOS和安卓渠道分开
	function recordOrder($orderLog, $paydbconn, $status, $money, $orderid,$thirdorderid='')
	{
		$sql = "SELECT * FROM {pre}payment WHERE orderid='{$orderid}'";
		$row = $paydbconn->one ( $sql );
		if ($row != null) {
			// 如果为已经记录下的订单
			if ($row ['status'] != STATUS_WAIT_CHARGE) {
				return TRUE;
			}
		} else {
			// echo " ChargeOrder: can not find order {$orderid} channel {$channelid} platform {$platform} \r\n";
			$orderLog->log ( "error", "ChargeOrder: can not find order {$orderid} channel {$row['channel']} platform {$row['platform']} \r\n" );
			return FALSE;
		}
		
		// 更新订单信息
		$now = date ( "Y-m-d H:i:s", time () );
		$jsonStr = json_encode ( $_REQUEST );
		
		$sql = "UPDATE {pre}payment SET `status`='{$status}',`finish_time`='{$now}',`content`='{$jsonStr}',`money`='{$money}',`thirdorderid`='{$thirdorderid}' WHERE orderid='{$orderid}' AND channel='{$row['channel']}' AND platform='{$row['platform']}' ";
		$res = $paydbconn->execute ( $sql );
		
		// 第几次充值
		$paytimes = 0;
		$sql = "SELECT * FROM {pre}payment WHERE serverid = " . $row ['serverid'] . " AND roleid='" . $row ['roleid'] . "'";
		$paydbconn->query ( $sql );
		$rolepayarr = array ();
		while ( $n = $paydbconn->get_array () ) {
			$rolepayarr [] = $n;
		}
		for($i = 0; $i < count ( $rolepayarr ); $i ++) {
			if (isset ( $rolepayarr [$i] ['money'] )) {
				$paytimes += 1;
			}
		}
		
		// 订单信息更新成功 开始发放充值
		if ($res !== FALSE && ($status == STATUS_SUCCESS || $status == 4)) { // 4表示补单的情况
			$serverInfo = $paydbconn->one ( "SELECT * FROM {pre}areasample WHERE `id`='" . $row ['serverid'] . "'" );
			$one ['orderid'] = ( string ) $row ['orderid'];
			$one ['roleid'] = ( int ) $row ['roleid'];
			$one ['channel'] = ( string ) $row ['channel'];
			$one ['money'] = ( string ) $money;
			$one ['platform'] = ( int ) $row ['platform'];
			$one ['finish_time'] = ( string ) $now;
			$one ['product_id'] = ( int ) $row ['product_id'];
			$one ['paytimes'] = $paytimes; // 累计支付次数
			$datas [] = $one;
			$json_str = json_encode ( $datas );
			$json_str = str_replace ( " ", "%20", $json_str );
			
			$strResult = vpost ( $serverInfo ['host'] . "json_str=$json_str&action=45", 10 ); // 请求游戏服务器发放充值
			                                                                              // 推送游戏服务器超时或者失败
			if ($strResult === FALSE || $strResult == "fail") {
				echo "error:area sending fail ";
				// 插入临时表格
				unset ( $row ['send_time'] );
				unset ( $row ['id'] );
				$res = $paydbconn->insert ( "{pre}payment_tmp", $row, true );
				if ($res == FALSE)
					$orderLog->log ( "error", "{$orderid} orderid insert into tmp_table error;" );
			}
		} else {
			// $this->log("error", "{$orderid} not STATUS_SUCCESS, something error");
			echo " ChargeOrder: {$orderid} not STATUS_SUCCESS, something error \r\n";
			return FALSE;
		}
		return TRUE;
	}
	
	function VstarOrder($orderLog, $paydbconn, $productid, $status, $money, $orderid,$thirdorderid='')
	{
		$sql = "SELECT * FROM {pre}payment WHERE orderid='{$orderid}' ";
		$row = $paydbconn->one ( $sql );
		if ($row != null) {
			// 如果为已经记录下的订单
			if ($row ['status'] != STATUS_WAIT_CHARGE) {
				return TRUE;
			}
		} else {
			// echo " ChargeOrder: can not find order {$orderid} channel {$channelid} platform {$platform} \r\n";
			$orderLog->log ( "error", "ChargeOrder: can not find order {$orderid} channel {$row['channel']} platform {$row['platform']} \r\n" );
			return FALSE;
		}
		
		// 更新订单信息
		$now = date ( "Y-m-d H:i:s", time () );
		$jsonStr = json_encode ( $_REQUEST );
		
		$sql = "UPDATE {pre}payment SET `status`='{$status}',`finish_time`='{$now}',`content`='{$jsonStr}',`money`='{$money}',`thirdorderid`='{$thirdorderid}', `product_id`='{$productid}' WHERE orderid='{$orderid}' AND channel='{$row['channel']}' AND platform='{$row['platform']}' ";
		$res = $paydbconn->execute ($sql);
		
		// 第几次充值
		$paytimes = 0;
		$sql = "SELECT * FROM {pre}payment WHERE serverid = " . $row ['serverid'] . " AND roleid='" . $row ['roleid'] . "'";
		$paydbconn->query ( $sql );
		$rolepayarr = array ();
		while ( $n = $paydbconn->get_array () ) {
			$rolepayarr [] = $n;
		}
		for($i = 0; $i < count ( $rolepayarr ); $i ++) {
			if (isset ( $rolepayarr [$i] ['money'] )) {
				$paytimes += 1;
			}
		}
		
		// 订单信息更新成功 开始发放充值
		if ($res !== FALSE && ($status == STATUS_SUCCESS || $status == 4)) { // 4表示补单的情况
			$serverInfo = $paydbconn->one ( "SELECT * FROM {pre}areasample WHERE `id`='" . $row ['serverid'] . "'" );
			$one ['orderid'] = ( string ) $row ['orderid'];
			$one ['roleid'] = ( int ) $row ['roleid'];
			$one ['channel'] = ( string ) $row ['channel'];
			$one ['money'] = ( string ) $money;
			$one ['platform'] = ( int ) $row ['platform'];
			$one ['finish_time'] = ( string ) $now;
			$one ['product_id'] = ( int ) $productid;
			$one ['paytimes'] = $paytimes; // 累计支付次数
			$datas [] = $one;
			$json_str = json_encode ( $datas );
			$json_str = str_replace ( " ", "%20", $json_str );
			
			$strResult = vpost ( $serverInfo ['host'] . "json_str=$json_str&action=45", 10 ); // 请求游戏服务器发放充值
			                                                                              // 推送游戏服务器超时或者失败
			if ($strResult === FALSE || $strResult == "fail") {
				echo "error:area sending fail ";
				// 插入临时表格
				unset ( $row ['send_time'] );
				unset ( $row ['id'] );
				$res = $paydbconn->insert ( "{pre}payment_tmp", $row, true );
				if ($res == FALSE)
					$orderLog->log ( "error", "{$orderid} orderid insert into tmp_table error;" );
			}
		} else {
			// $this->log("error", "{$orderid} not STATUS_SUCCESS, something error");
			echo " ChargeOrder: {$orderid} not STATUS_SUCCESS, something error \r\n";
			return FALSE;
		}
		return TRUE;
	}
	
	/*********************************************************************************************/
	
	//1.获取游戏区服列表的API
	function getarealist()
	{
		$arealist = get_area_list_detal();
		$sendarr = array();
		$tmparr = array();
		foreach ($arealist as $k => $v)
		{
			if ($v['name'] == 'happy')
				continue;
			$tmparr['id'] = $k;
			$tmparr['name'] = urlencode($v['name']);
			array_push($sendarr, $tmparr);
		}
		//var_dump(json_encode($sendarr));
		$tmpstr = http_build_query($sendarr);
		log_message("getarealist:".$tmpstr, "Vstar");
		echo json_encode($sendarr);
	}
	//2.获取游戏角色列表API
	function getrolelist()
	{
		include CONFIGPATH.'inc.php';
		include CONFIGPATH.'db.php';
		//Vstar服务器发过来的参数
		$userid = $_REQUEST['userid'];
		$serverid = $_REQUEST['serverid'];
		$str = "userid=".$userid."&serverid=".$serverid;
		log_message("getrolelist:".$str, "Vstar");
		
		$accountConn = new Database($config['center_db']);
		$sql = "SELECT id FROM account WHERE name = '$userid'";
		$one = $accountConn->one($sql);
		//通过账号id查到所有分区的角色id
		$arealist = get_area_list_detal();
		$sendarr = array();
		
		$conn = getTmpDbConnect(PLATFORM_ALL, 'all', $serverid, DBTYPE_GAMESERVER);
		if ($conn == false)
		{
			log_message("getrolelist:".$str." connect db $serverid failed", "Vstar");
			return;
		}
		$conn->query("SELECT id, name, profession FROM player WHERE accountid = ".$one['id']);
		$tmparr = array();
		while ($n = $conn->get_array())
		{
			$tmparr['role_id'] = $n['id'];
			$tmparr['role_name'] = $n['name'];
			$tmparr['prefession'] = $config['inc']['type_proffessionid'][$n['profession']];
			array_push($sendarr, $tmparr);
		}
		
		$tmpstr = http_build_query($sendarr);
		log_message("getrolelist:".$str.$tmpstr, "Vstar");
		echo json_encode($sendarr);
	}
	//3.礼包领取API
	function getgift()
	{
		include CONFIGPATH.'db.php';
		$ClientSecret = "327500d1bab9dc12f7dd1b1d3ffb1db8b15be219";
		/*userid	是	string	VstarGame平台账号ID
		serverid	是	string	游戏区服ID
		roleid	是	string	游戏角色ID
		key	是	string	礼包编号(游戏开发商提供)
		title	否	string	系统消息/邮件，标题
		content	否	string	系统消息/邮件，内容
		flag	是	string	md5(content key roleid serverid title userid ClientSecret) ,
		ClientSecret 请到“我的游戏”中查找
		注意：字符串间没有空格*/
		$userid = $_REQUEST['userid'];
		$serverid = $_REQUEST['serverid'];
		$roleid = $_REQUEST['roleid'];
		$key = $_REQUEST['key'];
		$title = $_REQUEST['title'];
		$content = $_REQUEST['content'];
		$flag = $_REQUEST['flag'];
		//userid=20000000008&serverid=1&roleid=1908&key=1800000003&title=邀请5人奖励&content=&flag=只要邀请Facebook好友，就可以获得邀请礼包哦！邀请越多，获得的奖励就越丰厚！赶快召集朋友们一起玩遊戏吧！每周都能重新邀请一次哦！
		$str = "userid=".$userid."&serverid=".$serverid."&roleid=".$roleid."&key=".$key."&title=".$title."&content=".$content."&flag=".$flag;
		log_message($str, "Vstar");
		//var_dump($str);
		//exit();
		$ret = array();  //返回
		
		$myflag = md5($content.$key.$roleid.$serverid.$title.$userid.$ClientSecret);
		if($flag == $myflag)
		//if(1)
		{
			//验证服务器是否存在
			$arealist = get_area_list_detal();
			if (!$arealist[$serverid])
			{
				$ret['status'] = false;
				$ret['code'] = 101;
				$ret['contents'] = "Server not found";
				log_message($str." Server not found", "Vstar");
				echo json_encode($ret);
				return;
			}
			//验证角色是否存在
			$conn = getTmpDbConnect(PLATFORM_ALL, 'all', $serverid, DBTYPE_GAMESERVER);
			$conn->query("SELECT id FROM player");
			$roleidlist = array();
			while($n = $conn->get_array())
			{
				$roleidlist[] = $n['id'];
			}
			if (!in_array($roleid, $roleidlist))
			{
				$ret['status'] = false;
				$ret['code'] = 102;
				$ret['contents'] = "Role not found";
				log_message($str." Role not found", "Vstar");
				echo json_encode($ret);
				return;
			}
			
			//判断此礼包是否是已有的三礼包中的一个(点赞礼包，分享礼包，邀请礼包)!!!!!!!!!!
			
			//此角色是否已领取了这个礼包
			$gmconn = new Database($config['db']);
			$sql = "SELECT * FROM vstar_giftstatus WHERE serverid = $serverid AND roleid = $roleid AND giftbagid = $key";
			$one = $gmconn->one($sql);
			if (isset($one))
			{
				$ret['status'] = false;
				$ret['code'] = 103;
				$ret['contents'] = "Key already used";
				log_message($str." Key already used", "Vstar");
				echo json_encode($ret);
				return;
			}
			$tmpret = self::sendGiftToPlayer($serverid, $roleid, $key, $title, $content);
			//b.记录存表
			if ($tmpret)
			{
				$nowtime = date("Y-m-d H:i:s", time());
				$sql = "INSERT INTO vstar_giftstatus(serverid, roleid, giftbagid, giftbagstatus, finishtime) VALUES(".
						$serverid.", ".$roleid.", '".$key."', 1, '$nowtime')";
				if($gmconn->execute($sql))
				{
					$ret['status'] = true;
					$ret['code'] = 1;
					$ret['contents'] = "success";
					log_message($str." success!!!", "Vstar");
					echo json_encode($ret);
					return;
				}
			}
			$ret['status'] = false;
			$ret['code'] = 104;
			$ret['contents'] = "other error";
			log_message($str." other error", "Vstar");
			echo json_encode($ret);
			return;	
		}
		else
		{
			$ret['status'] = false;
			$ret['code'] = 100;
			$ret['contents'] = "Signature error";
			log_message($str." Signature error", "Vstar");
			echo json_encode($ret);
			return;
		}
	}
		
	/*
	 * 发放奖励的接口
	 * @param $serverid为发送的服务器id
	 * @param $roleid为发送的角色id
	 * @param $key为礼包id
	 * @return 成功true，失败false
	 */
	static function sendGiftToPlayer($serverid, $roleid, $key, $title, $content) {
		// 获取到奖励物品信息
		include CONFIGPATH.'db.php';
		//$dynconn = getTmpDbConnect ( PLATFORM_ALL, 'all', $serverid, DBTYPE_DYNAMIC );
		$conn = new Database($config['center_db']);
		
		$rowdata = array ();
		$i = 0;
		$sql = "SELECT * FROM dynamic_giftbagdetail WHERE giftbagid = $key";
		$conn->query ( $sql );
		while ( $n = $conn->get_array () ) {
			$rowdata ['item'] [$i] = $n ['objectid'];
			$rowdata ['amount'] [$i] = $n ['maxcount'];
			$rowdata ['equiplevel'] [$i] = 0; // 装备等级，默认置0
			$i ++;
		}
		
		$strparam = "";
		$i = 0;
		while ( (! empty ( $rowdata ["item"] [$i] )) && (! empty ( $rowdata ["amount"] [$i] )) ) {
			$strparam .= "item$i=" . $rowdata ['item'] [$i] . "&amount$i=" . $rowdata ['amount'] [$i] . "&equiplv$i=" . $rowdata ['equiplevel'] [$i] . "&";
			$i ++;
		}
		
		$sendData = array ();
		// 填充基本信息
		$sendData ['mail_title'] = $title;
		$sendData ['keep_time'] = - 1; // 由游戏服来修改时间
		$sendData ['mail_content'] = $content;
		$sendData ['receiver_id'] = $roleid;
		
		$allurl = get_area_list_url ();
		$host = $allurl [$serverid];
		$strUrl = $host . array_to_stringparam ( $sendData ) . $strparam . "action=15"; // !!!!!注意权限过滤
		//var_dump($strUrl);
		//exit();                                                                      // print_r($strUrl);
		                                                                             // exit(0);
		$strResult = vpost ( $strUrl );
		if ($strResult == 1 || $strResult == 4) // 1是发送成功，4是转为离线发送
		{
			return true;
		}
		return false;
	}
		
}